// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <melon/init/init.h>
#include <algorithm>

#include <pollux/common/file/file_systems.h>
#include <pollux/common/memory/memory.h>
#include <pollux/dwio/common/reader.h>
#include <pollux/dwio/common/reader_factory.h>
#include <pollux/dwio/dwrf/register_dwrf_reader.h>
#include <pollux/common/file/temp_directory_path.h>
#include <pollux/vector/base_vector.h>

using namespace kumo::pollux;
using namespace kumo::pollux::dwio::common;
using namespace kumo::pollux::dwrf;

// A temporary program that reads from ORC file and prints its content
// Used to compare the ORC data read by DWRFReader against apache-orc repo.
// Usage: pollux_example_scan_orc {orc_file_path}
int main(int argc, char** argv) {
  melon::Init init{&argc, &argv};

  if (argc < 2) {
    return 1;
  }

  // To be able to read local files, we need to register the local file
  // filesystem. We also need to register the dwrf reader factory:
  filesystems::registerLocalFileSystem();
  dwrf::registerDwrfReaderFactory();
  kumo::pollux::memory::MemoryManager::initialize({});
  auto pool = kumo::pollux::memory::memoryManager()->addLeafPool();

  std::string filePath{argv[1]};
  dwio::common::ReaderOptions readerOpts{pool.get()};
  // To make DwrfReader reads ORC file, setFileFormat to FileFormat::ORC
  readerOpts.setFileFormat(FileFormat::ORC);
  auto reader = dwio::common::getReaderFactory(FileFormat::ORC)
                    ->createReader(
                        std::make_unique<BufferedInput>(
                            std::make_shared<LocalReadFile>(filePath),
                            readerOpts.memoryPool()),
                        readerOpts);

  VectorPtr batch;
  RowReaderOptions rowReaderOptions;
  auto rowReader = reader->createRowReader(rowReaderOptions);
  while (rowReader->next(500, batch)) {
    auto row_vector = batch->as<RowVector>();
    for (vector_size_t i = 0; i < row_vector->size(); ++i) {
      std::cout << row_vector->toString(i) << std::endl;
    }
  }

  return 0;
}
